<template>
  <div>
    <div class="address-ul">
      <ul>
        <li @click="selectCountryCode"><span>国家/地区：</span> <input type="text" v-model="countryName" disabled><i class="iconfont icon-xiayige"></i></li>
        <li><span>收货人：</span> <input type="text" v-model="name" :placeholder="nameTip"></li>
        <li>
          <span>联系电话：</span>
          <input type="tel" v-model="countryCode" disabled style="width:36px; flex: none;-webkit-flex: none">
          <input type="text" v-model="phone" maxlength="11">
        </li>
        <div v-if="isChinaFlag">
          <li><span>身份证号：</span> <input type="text" v-model="idcard" maxlength="18" placeholder="请输入身份证号"></li>
          <li><span>所在地区：</span>
              <view @click='chooseAddress' class="chooseAddress">
                <text>{{addr1}}</text>
                <i class="iconfont icon-xiayige"></i>
              </view>
          </li>
          <li><span>详细地址：</span> <input type="text" v-model="addr2" placeholder="请填写您的详细地址"></li>
        </div>

        <div v-else>
          <li><span>地址：</span> <input type="text" v-model="oaddr1"></li>
          <li><span>地址2：</span> <input type="text" v-model="oaddr2"></li>
          <li><span>市：</span> <input type="text" v-model="dataCity"></li>
          <li><span>州/省/地区：</span> <input type="text" v-model="district"></li>
          <li><span>邮编：</span> <input type="text" v-model="postcode"></li>
        </div>

        <li class="iddefault">
            <span>默认地址</span>
            <checkbox class="weui-check checkRight" :checked="isdefault" />
        </li>
      </ul>
    </div>

    <div class="address-id" @click="showIdcard"  v-if="isChinaFlag">
      	绑定身份信息 (非必填)
        <i class="iconfont icon-xiayige"></i>
        <font>{{auditStatusText}}</font>
    </div>
    <div class="address-id-tip" v-if="isChinaFlag">提示：上传身份证照片可加速清关。</div>
    <div class="address-id-tip" v-else>提示：请确认所填写的地址准确无误，避免造成订单无法正常发货。</div>

    <button class="weui-btn" type="primary" @click="postDate">确定</button>
    
    <nyz_area_picker :show="show"  @sureSelectArea="sureSelectAreaListener" @closePop="chooseAddress"></nyz_area_picker>

    <uploadIdcard :auditStatusData="auditStatus" @receiveIdcard="changeIdcard" @receiveCloseIdcard="closeIdcardPop" v-if="idcardPop"></uploadIdcard>
  </div>
</template>

<script>
import {mapActions} from 'vuex'
import uploadIdcard from '@/components/upload-idcard'
export default {
  data() {
    return {
      pageType:'',
      isChinaFlag:true,
      countryName:'中国',
      nameTip:'请与身份证姓名保持一致',
      countryCode: '+86',
      addressId:'',
      name:'',
      phone:'',
      idcard:'',
      oldIdCard:'',
      addr1:'',
      addr2:'',
      isdefault:true,
      idcardfront:'',
      idcardback:'',
      region: [],
      idcardPop: false,
      auditStatus:'',
      auditStatusText:'',
      /* 国外 */
      oaddr1:'',
      oaddr2:'',
      dataCity:'',
      district:'',
      postcode:'',

      /* 选择地址 */
      show:false
    }
  },
  onLoad() {
    Object.assign(this.$data, this.$options.data()); //重置data数据
    this.$wx.setTitleBarTitle('新增收货地址');
    this.addressId = this.$root.$mp.query.addressId;
    this.pageType = this.$root.$mp.query.type;
    if(this.addressId){
        this.getRess(this.addressId);
        this.$wx.setTitleBarTitle('修改收货地址');
    }
  },
  mounted() {
    if (!this.$wx.isArrayEmpty(this.$root.$eventHub._events.countryCodeChange)){
      this.$root.$eventHub.$off('countryCodeChange')
    }
    this.$root.$eventHub.$on('countryCodeChange', (item) => {
      this.countryName = item.chinese_name
      this.countryCode = item.code
      if(item.code == '+86'){
        this.isChinaFlag = true;
        this.nameTip = '请与身份证姓名保持一致'
      } else{
        this.isChinaFlag = false;
        this.nameTip = '请填写正确的收货人姓名'
      }
    })
  },
  destroyed() {
    this.$root.$eventHub.$off('countryCodeChange')
  },
  methods: {
    ...mapActions('cart', [
      'checkSettle'
    ]),
    sureSelectAreaListener(e){
      this.show = false;
      let selectAdd = e.mp.detail.currentTarget.dataset;
      this.addr1 = selectAdd.province + ' ' +selectAdd.city + ' ' +selectAdd.area;
    },
    chooseAddress(){
      this.show = !this.show
    },
    selectCountryCode() {
      this.$wx.jumper("../countrycode/main")
    },
    postDate(){
      var params = {};
      var checkArr = [];
      if (this.isChinaFlag) {
        if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.phone)) {
            this.$wx.showShortToast("请填写正确的手机号");
            return false;
        }

        if ((this.idcard=="") || ((this.oldIdCard != this.idcard) && !/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/.test(this.idcard))) {
            this.$wx.showShortToast("请填写正确的身份证");
            return false;
        }

        checkArr = [[this.name, "名字不能为空"],[this.addr1, "请选择地址"],[this.addr2, "地址详情不能为空"]];
        params = {
          country_code: this.countryCode,
          address_country: this.countryName,
          address: this.addr1 + " " + this.addr2,
          is_default: this.isdefault,
          consignee_name: this.name,
          consignee_phone: this.phone,
          consignee_idcard: this.idcard,
          consignee_idcard_front: this.idcardfront,
          consignee_idcard_back: this.idcardback
        }
      } else{
        checkArr = [[this.name, "名字不能为空"],[this.oaddr1, "地址不能为空"], [this.dataCity, "市不能为空"], [this.district, "州/省/地区不能为空"], [this.postcode, "邮编不能为空"]];
        params = {
          country_code: this.countryCode,
          address_country: this.countryName,
          is_default: this.isdefault,
          consignee_name: this.name,
          consignee_phone: this.phone,
          address: this.oaddr1,
          address2: this.oaddr2,
          city: this.dataCity,
          district: this.district,
          postcode: this.postcode
        }
      }

      if (!this.$wx.nullValueCheck(checkArr)) {
          return false;
      }

      var url = this.$url.URL_ADDRESS;
      if (this.addressId) {
          url = this.$url.URL_MODIFYADDRESS;
          params.address_id = this.addressId;
      }
      this.AddRess(url,params)
    },
    //新增、修改
    async AddRess(url,params) {
      const data = await this.$fly.post(url,params)
      if (data.successCode === 1) {
        if(this.pageType == 'cashier'){
          console.log(110)
          await this.checkSettle({isSettlePage:true})
        }
        wx.navigateBack({delta:1})
      }
    },
    //获取
    async getRess(addressId) {
      const data = await this.$fly.post(this.$url.URL_GETADDRESS, {
        address_id:addressId
      })
      if (data.successCode === 1) {
         var addressData = data.data;
         this.countryName = addressData.address_country;
         this.name = addressData.consignee_name;
         this.phone = addressData.consignee_phone;

         if(addressData.country_code == '+86'){
            this.isChinaFlag = true;
            this.idcard = addressData.consignee_idcard;
            this.oldIdCard = addressData.consignee_idcard;
            this.isdefault = addressData.is_default;
            var addrArr = addressData.address.split(" ");
            this.addr1 = addrArr[0];
            this.region = addrArr[0].split(',');
            this.province = this.region[0];
            this.city = this.region[1];
            this.area = this.region[2];

            this.addr2 = addrArr.pop();
            this.auditStatus = addressData.audit_status;
            switch(addressData.audit_status){
                case "PASSED":
                    this.auditStatusText = "已通过"
                    break;
                case "REIVEW":
                    this.auditStatusText = "审核中"
                    break;
                default:
                    break;
            }
         } else{
           this.isChinaFlag = false;
           this.address_country = addressData.address_country;
           this.oaddr1 = addressData.address;
           this.oaddr2 = addressData.address2;
           this.dataCity = addressData.city;
           this.district = addressData.district;
           this.postcode = addressData.postcode
         }

         
      }
    },
    changeIdcard(path,type){
      if(type == 'idcardfront'){
        this.idcardfront = path
      } else{
        this.idcardback = path
      }
    },
    showIdcard(){
      this.idcardPop = true
    },
    closeIdcardPop(){
      this.idcardPop = false
    }
  },
  components: {
    uploadIdcard
  }
}
</script>

<style scoped>
.address-ul{padding:0 4%; background-color: #fff; overflow: hidden; border-width:1px 0; border-color:#f2f2f2; border-style: solid;}
.address-ul ul li{border-bottom:1px #f5f5f5 solid; line-height: 36px; padding:2% 0; overflow: hidden; position: relative; display: -webkit-box; display: -webkit-flex; display: flex;}
.address-ul ul li.iddefault{border-bottom: none; position: relative;}
.address-ul ul li.iddefault span{color: #ff4545}
.checkRight{position: absolute; top: 3px; right:0;}
.address-ul ul li span{display: block; width:86px}
.address-ul ul li input,.address-ul ul li .chooseAddress{height: 34px; -webkit-box-flex: 1; -webkit-flex: 1; flex: 1; display: block;}
.address-ul ul li .addInput{flex: 1;-webkit-flex: 1; height: 34px;}
.address-ul ul li i{position: absolute; right:0; top:50%; -webkit-transform: translateY(-50%); transform: translateY(-50%);}

.weui-btn{margin: 30px 10px 0; background: #000}

.address-id{padding:2% 4%; margin-top:12px; background-color: #fff; border-bottom:1px #f2f2f2 solid; border-top:1px #f2f2f2 solid; position: relative;}
.address-id font{float:right; margin-right:20px; font-weight: bold}
.address-id i{float: right;}
.address-id-tip{padding:1% 4%; font-size: .8em; color:#999}
</style>
